package com.onenine.app.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.app.ActivityCompat;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.onenine.app.R;
import com.onenine.app.model.CommentParent;
import com.onenine.app.model.CommentSub;
import com.onenine.app.utils.DataType;
import com.onenine.chat.util.SimpleCommonUtils;
import com.onenine.common.util.ApUtils;

import java.util.List;

/**
 * 评论列表
 */
public class CommentListView extends LinearLayout {

    private static final int LOAD_MORE_COUNT = 3;   //3条后折叠显示
    private int itemSelectorColor;
    private OnItemClickListener onItemClickListener;
    private List<CommentSub> mDataList;
    private LayoutInflater layoutInflater;
    private CommentParent mCommentParent;
    private int txtPadding;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setDataList(CommentParent commentParent) {
        if (commentParent == null) {
            return;
        }
        mCommentParent = commentParent;
        mDataList = commentParent.getCommentSub();
        notifyDataSetChanged();
    }

    public CommentListView(Context context) {
        super(context);
    }

    public CommentListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(attrs);
    }

    public CommentListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(attrs);
    }

    protected void initAttrs(AttributeSet attrs) {
        txtPadding = getResources().getDimensionPixelOffset(R.dimen.dp6);
        setOrientation(VERTICAL);
        TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.CommentListView, 0, 0);
        try {
            itemSelectorColor = typedArray.getColor(R.styleable.CommentListView_item_selector_color, 0xffe9e9e9);
        } finally {
            typedArray.recycle();
        }
    }

    /**
     * 通知刷新
     */
    public void notifyDataSetChanged() {
        if (mDataList == null || mDataList.size() == 0) {
            return;
        }
        removeAllViews();
        if (mCommentParent != null
                && mCommentParent.isSubExpand() || mDataList.size() <= LOAD_MORE_COUNT) {
            //全部显示
            addCommentViews(mDataList);
        } else {
            //折叠显示
            addCommentViews(mDataList.subList(0, LOAD_MORE_COUNT));
            addView(getCollapseView(mDataList.subList(LOAD_MORE_COUNT, mDataList.size())));
        }
    }

    /**
     * 添加子评论
     *
     * @param commentList
     */
    private void addCommentViews(List<CommentSub> commentList) {
        for (int i = 0; i < commentList.size(); i++) {
            addView(getSubCommentView(i));
        }
    }

    /**
     * 生成折叠提示
     *
     * @return
     */
    private View getCollapseView(List<CommentSub> restList) {
        TextView colView = new TextView(getContext());
        colView.setPadding(txtPadding, txtPadding, txtPadding, txtPadding);
        colView.setText(R.string.see_all_comment);
        colView.setTextSize(12);
        colView.setTextColor(0XFF4A90E2);
        colView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                CommentListView.this.removeView(colView);
                addCommentViews(restList);
                if (mCommentParent != null) {
                    mCommentParent.setSubExpand(true);
                }
            }
        });
        return colView;
    }

    /**
     * 生成子评论项
     *
     * @param position
     * @return
     */
    private View getSubCommentView(final int position) {
        if (layoutInflater == null) {
            layoutInflater = LayoutInflater.from(getContext());
        }
        final CommentSub commentSub = mDataList.get(position);
        View convertView;
        if (commentSub.getcType() == DataType.COMMENT_VOICE_TYPE) {
            //语音评论
            convertView = layoutInflater.inflate(R.layout.layout_sub_comment_voice_item, null, false);
            TextView tvName = convertView.findViewById(R.id.tv_name);
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append(commentSub.getNickName());
            int startIndex = builder.length();
            if (commentSub.getCommentSubType() == 2 && !TextUtils.isEmpty(commentSub.getTargetUserName())) {
                String replyStr = " 回复 ";
                builder.append(replyStr);
                builder.append(commentSub.getTargetUserName());
            }
            builder.append("：");
            builder.setSpan(new ForegroundColorSpan(ActivityCompat.getColor(ApUtils.getApp(), R.color.c333))
                    , 0, startIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvName.setText(builder);
            NVoiceBar nVoiceBar = convertView.findViewById(R.id.nv_voice);
            nVoiceBar.setSmallStyle();
            nVoiceBar.setSexStyle(commentSub.getSex(), true);
            nVoiceBar.setVoiceLengthVisible(false);
            nVoiceBar.setData(commentSub.getCommentSubDesc(), 0f);
        } else {
            //文本评论
            convertView = layoutInflater.inflate(R.layout.layout_sub_comment_text_item, null, false);
            TextView commentTv = convertView.findViewById(R.id.tv_comment);
            final CircleMovementMethod circleMovementMethod = new CircleMovementMethod(itemSelectorColor, itemSelectorColor);
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append(commentSub.getNickName());
            int startIndex = builder.length();
            int replyIndex = 0;
            if (commentSub.getCommentSubType() == 2 && !TextUtils.isEmpty(commentSub.getTargetUserName())) {
                String replyStr = " 回复 ";
                builder.append(replyStr);
                builder.append(commentSub.getTargetUserName());
                replyIndex = replyStr.length();
            }
            builder.append("：");
            int endIndex = builder.length();
            builder.append(commentSub.getCommentSubDesc());
            SpannableStringBuilder ssb = new SpannableStringBuilder(builder.toString());
            if (endIndex < builder.length()) {
                ssb.setSpan(new ForegroundColorSpan(ActivityCompat.getColor(ApUtils.getApp(), R.color.c333))
                        , 0, startIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ssb.setSpan(new ForegroundColorSpan(ActivityCompat.getColor(ApUtils.getApp(), R.color.c333))
                        , startIndex + replyIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            SimpleCommonUtils.spannableEmoticonFilter(commentTv, ssb, builder.toString());
            commentTv.setMovementMethod(circleMovementMethod);
            commentTv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (circleMovementMethod.isPassToTv()) {
                        if (onItemClickListener != null) {
                            onItemClickListener.onItemClick(position);
                        }
                    }
                }
            });
        }
        return convertView;
    }

}
